﻿#include "ControlItem.h"
#include "ItemBase.h"
#include <QDebug>

//构造函数
ControlItem::ControlItem(QGraphicsItem* parent, QPointF p, ControlPointType type)
    : QAbstractGraphicsShapeItem(parent), 
      mPointType(type),
      mCurPoint(p),
      mPrePoint(p),  // 初始时，前一个点等于当前点
      mOffsetX(0),
      mOffsetY(0),
      mPen(QPen(Qt::black))  // 显式初始化 mPen
{
    setPos(mCurPoint);
    setCursor(mPointType == CPT_Center ? Qt::OpenHandCursor : Qt::PointingHandCursor);
    setBrush(QBrush(QColor(0, 100, 250)));
    setCacheMode(DeviceCoordinateCache);
    
    setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable | ItemStopsFocusHandling);
    
    mRect = QRectF(-ItemBase::contrSize, -ItemBase::contrSize, ItemBase::contrSize * 2, ItemBase::contrSize * 2);
    mPen.setWidthF(0); // 线宽始终为1像素，防止缩放问题
}



void ControlItem::setPoint(QPointF p)
{
    if (mCurPoint != p) {  // 避免不必要的更新
        mCurPoint = p;
        setPos(mCurPoint);
    }
}


//拖拽 鼠标感应区域
QRectF ControlItem::boundingRect() const
{
    return mRect;
}

//位置重绘
void ControlItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
	//位置重绘
	Q_UNUSED(option);
	Q_UNUSED(widget);
    painter->setPen(mPen);
	painter->setBrush(this->brush());
    if (mPointType == CPT_Center) {
        painter->drawRect(mRect);
	}else{
		//浮点型椭圆、整数椭圆缩放时会出问题
        painter->drawEllipse(mRect);
	}
}

//鼠标事件处理
void ControlItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    auto* item = dynamic_cast<ItemBase*>(this->parentItem());
    if (!item) return;  // 保护性检查，避免崩溃

    mOffsetX = event->scenePos().x() - event->lastScenePos().x();
    mOffsetY = event->scenePos().y() - event->lastScenePos().y();

    if (mPointType == CPT_Center) {
        item->moveBy(mOffsetX, mOffsetY);
    } else {
        mPrePoint = mCurPoint;
        mCurPoint = mapToParent(event->pos());

        if (item->itemUpdate(item->controlList.indexOf(this))) {
            setPos(mCurPoint);
        } else {
            mCurPoint = mPrePoint;
            setPos(mCurPoint);
        }
    }
}


void ControlItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
    auto* item = dynamic_cast<ItemBase*>(this->parentItem());
    if (item && mPointType == CPT_Center) {
        item->setFocus();
        item->setSelected(true);
    }
    QGraphicsItem::mouseDoubleClickEvent(event);
}

